<template>
    <component :is="config.layout.layoutMode"></component>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useConfig } from '/@/stores/config'
import { useNavTabs } from '/@/stores/navTabs'
import { useTerminal } from '/@/stores/terminal'
import { useSiteConfig } from '/@/stores/siteConfig'
import { useAdminInfo } from '/@/stores/adminInfo'
import { useRoute } from 'vue-router'
import Default from '/@/layouts/backend/container/default.vue'
import Classic from '/@/layouts/backend/container/classic.vue'
import Streamline from '/@/layouts/backend/container/streamline.vue'
import Double from '/@/layouts/backend/container/double.vue'
import { onMounted, onBeforeMount } from 'vue'
import { Session } from '/@/utils/storage'
import { index } from '/@/api/backend'
import { handleAdminRoute, getFirstRoute, routePush } from '/@/utils/router'
import router from '/@/router/index'
import { adminBaseRoutePath } from '/@/router/static/adminBase'
import { useEventListener } from '@vueuse/core'
import { BEFORE_RESIZE_LAYOUT } from '/@/stores/constant/cacheKey'
import { isEmpty } from 'lodash-es'
import { setNavTabsWidth } from '/@/utils/layout'

defineOptions({
    components: { Default, Classic, Streamline, Double },
})

const terminal = useTerminal()
const navTabs = useNavTabs()
const config = useConfig()
const route = useRoute()
const siteConfig = useSiteConfig()
const adminInfo = useAdminInfo()

const state = reactive({
    autoMenuCollapseLock: false,
})

onMounted(() => {
    if (!adminInfo.token) return router.push({ name: 'adminLogin' })

    init()
    setNavTabsWidth()
    useEventListener(window, 'resize', setNavTabsWidth)
})
onBeforeMount(() => {
    onAdaptiveLayout()
    useEventListener(window, 'resize', onAdaptiveLayout)
})

const init = () => {
    /**
     * 后台初始化请求，动态路由等信息
     */
    index().then((res) => {
        // siteConfig.dataFill(res.data.siteConfig)
        // terminal.changePackageManager(res.data.terminal.npmPackageManager)
        // terminal.changePHPDevelopmentServer(res.data.terminal.phpDevelopmentServer)
        // siteConfig.setInitialize(true)

        if (!isEmpty(res.data.adminInfo)) {
            adminInfo.dataFill(res.data.adminInfo)
            siteConfig.setUserInitialize(true)
        }

        if (res.data.menuList) {
            // 将menuList转换为handleAdminRoute需要的格式
            const convertMenu = (menu: any) => {
                // 根据menu.type确定正确的路由类型
                let routeType = 'menu' // 默认为menu类型
                let menuType = 'tab' // 默认为tab类型

                if (menu.type === 'folder') {
                    routeType = 'menu_dir' // 文件夹类型对应menu_dir
                } else if (menu.type === 'file') {
                    routeType = 'menu' // 文件类型对应menu
                    menuType = 'tab' // 文件类型通常是tab类型菜单
                }

                // 处理children可能是对象的情况
                let childrenArray = []
                if (menu.children) {
                    if (Array.isArray(menu.children)) {
                        childrenArray = menu.children
                    } else if (typeof menu.children === 'object' && menu.children !== null) {
                        // 如果children是对象，将其转换为数组
                        childrenArray = Object.values(menu.children)
                    }
                }
                return {
                    id: menu.id,
                    type: routeType,
                    menu_type: menuType,
                    pid: menu.pid,
                    name: menu.name,
                    path: menu.path || menu.name.toLowerCase().replace(/\s+/g, '_'),
                    title: menu.title,
                    icon: menu.icon || '',
                    component: menu.component || "admin/index",
                    meta: {
                        id: menu.id,
                        type: routeType,
                        menu_type: menuType,
                        pid: menu.pid,
                        title: menu.title,
                        icon: menu.icon || '',
                    },
                    children: childrenArray.length > 0 ? childrenArray.map((child: any) => convertMenu(child)) : [],
                }
            }

            // 转换菜单数据 - 确保menuList是数组格式
            let menuListArray = []
            if (Array.isArray(res.data.menuList)) {
                menuListArray = res.data.menuList
            } else if (typeof res.data.menuList === 'object' && res.data.menuList !== null) {
                // 如果是对象格式，转换为数组
                menuListArray = Object.values(res.data.menuList)
            }

            const convertedMenus = menuListArray.map((menu: any) => convertMenu(menu))
            console.log('转换后的菜单数据:', convertedMenus)

            // 处理路由
            try {
                if (convertedMenus && convertedMenus.length > 0) {
                    handleAdminRoute(convertedMenus)
                    console.log('处理后的路由:', navTabs.state.tabsViewRoutes)
                }
            } catch (error) {
                console.error('处理路由时出错:', error)
            }

            // 预跳转到上次路径
            if (route.params.to) {
                try {
                    console.log('处理to参数:', route.params.to)
                    let targetRoute: any

                    // 检查参数类型并正确解析
                    if (typeof route.params.to === 'string') {
                        try {
                            // 尝试解析为JSON对象
                            targetRoute = JSON.parse(route.params.to)
                        } catch (e) {
                            // 如果不是有效的JSON，直接使用字符串作为路径
                            targetRoute = { path: route.params.to }
                        }
                    } else {
                        targetRoute = route.params.to
                    }

                    // 确保path存在且不是基础路径
                    if (targetRoute.path && targetRoute.path !== adminBaseRoutePath) {
                        console.log('准备跳转到:', targetRoute.path)
                        let query = !isEmpty(targetRoute.query) ? targetRoute.query : {}
                        routePush({ path: targetRoute.path, query: query })
                        return
                    }
                } catch (error) {
                    console.error('解析上次路径时出错:', error)
                }
            }

            // 跳转到第一个菜单
            setTimeout(() => {
                let firstRoute = getFirstRoute(navTabs.state.tabsViewRoutes)
                console.log('第一个路由:', firstRoute)
                if (firstRoute) {
                    routePush(firstRoute.path)
                } else {
                    // 添加默认跳转逻辑，确保即使没有找到第一个路由也能跳转到dashboard
                    console.log('未找到第一个路由，跳转到默认的dashboard页面')
                    routePush(adminBaseRoutePath + '/dashboard')
                }
            }, 100)
        }
    })
}

const onAdaptiveLayout = () => {
    let defaultBeforeResizeLayout = {
        layoutMode: config.layout.layoutMode,
        menuCollapse: config.layout.menuCollapse,
    }
    let beforeResizeLayout = Session.get(BEFORE_RESIZE_LAYOUT)
    if (!beforeResizeLayout) Session.set(BEFORE_RESIZE_LAYOUT, defaultBeforeResizeLayout)

    const clientWidth = document.body.clientWidth
    if (clientWidth < 1024) {
        /**
         * 锁定窗口改变自动调整 menuCollapse
         * 避免已是小窗且打开了菜单栏时，意外的自动关闭菜单栏
         */
        if (!state.autoMenuCollapseLock) {
            state.autoMenuCollapseLock = true
            config.setLayout('menuCollapse', true)
        }
        config.setLayout('shrink', true)
        config.setLayoutMode('Classic')
    } else {
        state.autoMenuCollapseLock = false
        let beforeResizeLayoutTemp = beforeResizeLayout || defaultBeforeResizeLayout

        config.setLayout('menuCollapse', beforeResizeLayoutTemp.menuCollapse)
        config.setLayout('shrink', false)
        config.setLayoutMode(beforeResizeLayoutTemp.layoutMode)
    }
}
</script>
